package plugins

import (
	"os"
	"strings"
	"testing"
)

const (
	testConfigDir   = "testdata"
	testSuffixesDir = "testdata/suffixes"
	testPluginFile  = "testdata/plugins/test/manifest.yaml"
)

// helpers

// WithConfigDir sets custom configuration dir
func WithConfigDir(t testing.TB, dir string) {
	orig := ConfigDir
	ConfigDir = func() string {
		return dir
	}

	t.Cleanup(func() {
		ConfigDir = orig
	})
}

// tests

func Test_configDir(t *testing.T) {
	// just registers code coverage
	t.Run("ok", func(in *testing.T) {
		configDir()
	})
}

func Test_collectBySuffix(t *testing.T) {
	t.Run("ok", func(sub *testing.T) {
		// emulate de-duplications
		paths := []string{testSuffixesDir, testSuffixesDir, "no-dir-found"}
		sub.Setenv("PATH", strings.Join(paths, string(os.PathListSeparator)))
		plugins := collectBySuffix()
		expected := 1
		if result := len(plugins); result != expected {
			sub.Errorf("expected: %d, got: %d", expected, result)
		}
	})

	t.Run("path-is-not-set", func(sub *testing.T) {
		orig := os.Getenv("PATH")
		_ = os.Unsetenv("PATH")
		defer func() {
			_ = os.Setenv("PATH", orig)
		}()

		collectBySuffix()
	})
}

func TestLoadPlugins(t *testing.T) {
	t.Setenv("PATH", testConfigDir) // disabling collectBySuffix

	t.Run("ok", func(sub *testing.T) {
		WithConfigDir(sub, testConfigDir)
		plugins := LoadPlugins()
		expected := 1
		if result := len(plugins); result != expected {
			sub.Errorf("expected: %d, got: %d", expected, result)
		}
	})

	t.Run("cant-read-dir", func(sub *testing.T) {
		WithConfigDir(sub, testScriptFile)
		if plugins := LoadPlugins(); len(plugins) != 0 {
			sub.Errorf("plugins amount expected to be 0")
		}
	})
}

func TestPluginFromFile(t *testing.T) {
	t.Run("ok", func(sub *testing.T) {
		if _, err := PluginFromFile(testPluginFile); err != nil {
			sub.Errorf("got error: %v", err)
		}
	})

	t.Run("file-not-found", func(sub *testing.T) {
		if _, err := PluginFromFile("non-existent-file"); err == nil {
			sub.Errorf("expected error but got nil instead")
		}
	})
}
